from flask_shop.user import user_bp,user_api
#此模块需要用User,而且需要把module文件加载一下
from flask_shop.models import User
from flask_shop import db
from flask import request
from flask_restful import Resource,reqparse
import re
from flask_shop.utils.token import generate_token,verify_token,login_required


@user_bp.route('/',methods=['get','post'])
def index():
    return 'hello user'


@user_bp.route('/login/',methods=['post'])
def login():
    uname = request.get_json().get('name')
    pwd = request.get_json().get('pwd')
    if not all([uname,pwd]):
        return {'status':'400','msg':'用户名或密码为空'}
    else:
        #通过用户名查询用户对象
        user = User.query.filter(User.name == uname).first()
        if user:
            #判断密码是否正确
            if user.check_password(pwd):
                token = generate_token({'id':user.id})
                # pyload = verify_token(token) 用于测试
                return {'status':'200','msg':'登录成功','data':{'token':token}}
            else:
                return {'status':'400','msg':'密码错误'}
        else:
            return {'status':'400','msg':'用户不存在'}
        

class Users(Resource):
    def get(self):
        #创建requestParser对象
        parser = reqparse.RequestParser()
        parser.add_argument('pnum',type=int,location='args')
        parser.add_argument('psize',type=int,location='args')
        parser.add_argument('name',type=str,location='args')
        #解析数据
        args = parser.parse_args()
        #获取参数
        name = args.get('name')
        pnum = args.get('pnum')
        psize = args.get('psize')
        #判断是否传递了name
        if name:
            #获取用户列表
            user_list = User.query.filter(User.name.like(f'%{name}%')).paginate(page=pnum,per_page=psize)
        else:
            user_list = User.query.paginate(page=pnum,per_page=psize)
        data = {
            'total':user_list.total,
            'pnum':pnum,
            'data':[u.to_dict() for u in user_list.items]
            }
        return {'status':200,'msg':'获取成功','data':data}

    def post(self):
        name = request.get_json().get('name')
        pwd = request.get_json().get('pwd')
        required_pwd = request.get_json().get('required_pwd')
        nick_name = request.get_json().get('nick_name')
        phone = request.get_json().get('phone')
        email = request.get_json().get('email')
        rid = request.get_json().get('rid')
        if not rid:
            rid = 3#默认普通用户
        if not all([name,pwd,required_pwd]):
            return {'status':400,'msg':'必填项存在空项'}
        try:
            user = User.query.filter(User.name == name).first()
            if user:
                return {'status':888,'msg':'用户名已存在'}
        except Exception as e:
            print(e)
        if not re.match(r'^1[356789]\d{9}$',phone):
            return {'status':400,'msg':'手机号不合法'}
        if not re.match('^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$',email):
            return {'status':400,'msg':'邮箱不合法'}
        user = User(name=name,password=pwd,nick_name=nick_name,phone=phone,email=email,rid=rid)
        db.session.add(user)
        db.session.commit()
        return {'status':200,'msg':'注册成功！'}


class User_Handle(Resource):
    def get(self,id):
        user = User.query.get(id)
        if user:
            return {'status':200,'msg':'获取成功','data':user.to_dict()}
        else:
            return {'status':404,'msg':'用户不存在'}
    def put(self,id):
        try:
            db_user = User.query.get(id)
            #创建requestParse对象，用来接收数据
            paser = reqparse.RequestParser()
            paser.add_argument('name',type=str)
            paser.add_argument('nick_name',type=str)
            paser.add_argument('phone',type=str)
            paser.add_argument('email',type=str)
            paser.add_argument('rid',type=int)
            #解析数据
            args = paser.parse_args()
            if args.get('name'):
                db_user.name = args.get('name')
            if args.get('nick_name'):
                db_user.nick_name = args.get('nick_name')
            if args.get('phone'):
                db_user.phone = args.get('phone')
            if args.get('email'):
                db_user.email = args.get('email')
            if args.get('rid'):
                db_user.rid = args.get('rid')
            db.session.commit()
            return {'status':200,'msg':'修改成功','data':db_user.to_dict()}
        except Exception as e:
            print(e)
            return {'status':400,'msg':'修改失败'}
        
    def delete(self,id):
        try:
            user = User.query.get(id)
            if user:
                db.session.delete(user)
                db.session.commit()
                return {'status':200,'msg':'删除成功'}
            else:
                return {'status':400,'msg':'用户不存在，删除失败'}
        except Exception as e:
            print(e)
            return {'status':400,'msg':'删除失败'}

user_api.add_resource(Users,'/users/')
user_api.add_resource(User_Handle,'/user/<int:id>/')

@user_bp.route('/reset_pwd/<int:id>/')
def reset_pwd(id):
    try:
        user = User.query.get(id)
        if user:
            user.password = '123456'
            db.session.commit()
            return {'status':200,'msg':'密码重置成功'}
    except Exception as e:
        return {'status':400,'msg':'密码重置失败'}

@user_bp.route('/test/')
@login_required
def login_required():
    return {'status':200,'msg':'验证成功'}